package com.neo.controller;

import com.neo.remote.HelloRemote;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@RestController
public class ConsumerController {

    @Autowired
    HelloRemote HelloRemote;
	
    @RequestMapping("/hello/{name}")
    public String index(@PathVariable("name") String name) {
        return HelloRemote.hello(name);
    }
    /**
     * 模拟创建文件类型数据
     */
    @RequestMapping("/upload/{name}")
    public String upload(@PathVariable("name") String name) {
    	 File file = new File("upload.txt");
         DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
                 MediaType.TEXT_PLAIN_VALUE, true, file.getName());

         try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
             IOUtils.copy(input, os);
         } catch (Exception e) {
             throw new IllegalArgumentException("Invalid file: " + e, e);
         }
         MultipartFile multi = new CommonsMultipartFile(fileItem);
        return HelloRemote.upload(multi);
    }

}